package org.dcarew.clearcase;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.resources.IResource;

/**
 * 
 * 
 * @author Devon Carew
 */
class DBFileInfo
{
    private long lastModified;
    
    private Map<String, DBFileEntry> filenameMap = new HashMap<String, DBFileEntry>();
    
    
    DBFileInfo(File file)
    {
        try
        {
            parse(file);
        }
        catch (IOException ce)
        {
            // TODO:
            
            ce.printStackTrace();
        }
    }
    
    public DBFileEntry getFileEntry(IResource resource)
    {
        return filenameMap.get(resource.getName());
    }
    
    public long getLastModified()
    {
        return lastModified;
    }
    
    private void parse(File file)
        throws IOException
    {
        lastModified = file.lastModified();
        
        BufferedReader reader = new BufferedReader(new FileReader(file));
        
        reader.readLine();
        reader.readLine();
        reader.readLine();
        reader.readLine();
        
        String line = reader.readLine();
        
        while (line != null)
        {
            parseFileEntry(file.getParentFile(), line);
            
            line = reader.readLine();
        }
        
        reader.close();
    }
    
    private void parseFileEntry(File parent, String line)
    {
        // e:Predicate.java|1|124c0652976|1e9|7d9196f3|ff4c6e4a0adf4d13a292ab21034bcc1f|0
        
        // 0=name
        // 1=? file == 1, folder == 2
        // 2=?
        // 3=file length
        // 4=?
        // 5=crc ?
        // 6=checked out?
        
        String[] params = line.split("\\|");
        
        String fileName = ccParseString(params[0]);
        
        DBFileEntry entry = new DBFileEntry(parent, fileName);
        
        //int resourceType = Integer.parseInt(params[1]);
        int checkedOutVal = Integer.parseInt(params[6]);
        int scmLength = Integer.parseInt(params[3], 16);
        
        entry.setCheckedOut(checkedOutVal > 0);
        entry.setSCMLength(scmLength);
        
        filenameMap.put(fileName, entry);
    }

    private String ccParseString(String str)
    {
        if (str.indexOf(":") != -1)
            str = str.substring(str.indexOf(":") + 1);
        
        return str;
    }

}
